
const fs = require('fs')
const dbPath = './db.json'

//学生列表
let find = callback => {
	fs.readFile(dbPath,'utf8', (err, data) => {
		if(err){
			return callback(err)
		}
		let students = JSON.parse(data).students
		callback(null,students)
	})
}

//保存新增学生
let save = (stu, callback) => {
	fs.readFile(dbPath, 'utf8', (err, data) => {
		if(err){
			return callback(err)
		}
		let students = JSON.parse(data).students
		if (students.length > 0) {
			stu.id = students[students.length-1].id + 1
		} else {
			stu.id = 1;
		}
		students.push(stu)

		var fileData = JSON.stringify({ students: students })
		fs.writeFile(dbPath, fileData, err => {
			if(err){
				return callback(err)
			}
			callback(null)
		})
	})
}

//已有学生编辑
let edit = (id, callback) => {
	fs.readFile(dbPath, 'utf8', (err, data) => {
		if(err){
			return callback(err)
		}
		let students = JSON.parse(data).students
		let stu = students.find( item => {
			return item.id == parseInt(id)
		})
		callback(null, stu)
	})
}

//已有学生编辑保存
let editSave = (stu, callback) => {
	fs.readFile(dbPath, 'utf8', (err, data) => {
		if(err){
			return callback(err)
		}
		let students = JSON.parse(data).students
		let stuIndex = students.findIndex( item => {
			return item.id === parseInt(stu.id)
		})
		students[stuIndex] = stu
		let fileData = JSON.stringify({students: students})
		fs.writeFile(dbPath, fileData, err => {
			if(err){
				return callback(err)
			}
			callback(null)
		})
	})
}


//已有学生删除
let del = (id, callback) => {
	fs.readFile(dbPath, 'utf8', (err, data) => {
		if(err){
			return callback(err)
		}
		let students = JSON.parse(data).students
		let stuIndex = students.findIndex( item => {
			return item.id = parseInt(id)
		})
		students.splice(stuIndex, 1)
		let fileData = JSON.stringify({students: students})
		fs.writeFile(dbPath, fileData, err => {
			if(err){
				return callback(err)
			}
			callback(null)
		})
	})
}








module.exports = {
	find,
	save,
	edit,
	editSave,
	del
}